import React, { Component } from 'react'
import { Card, Form, Input, Cascader, Upload, Button, message } from 'antd'
import PicturesWall from './Pictures-wall'
import RichTextEditor from './RichTextEditor'

import LinkButton from '../../components/link-button'
import { ArrowLeftOutlined, LoadingOutlined, PlusOutlined } from "@ant-design/icons"

import { reqCategory, reqCategorys, reqCategroys, reqAddProduct } from '../../api'

const { Item } = Form
const { TextArea } = Input

export default class ProductAddUpdate extends Component {

  state = {
    options: []
  }

  // 价格验证
  validatePrice = (rule, value, callback) => {
    callback() //验证通过
    if (value < 0) {
      return Promise.reject(new Error('价格不能小于0'))
    } else {
      return Promise.resolve() //验证通过
    }
  }

  getCategorys = async (parentId) => {
    const result = await reqCategorys(parentId)
    if (result.data.status === 0) {
      let options = []
      result.data.data.forEach(item => {
        options.push({ value: item._id, label: item.name, isLeaf: false })
      })
      this.setState({ options: options })
    }
  }

  componentDidMount() {
    this.getCategorys()
  }

  componentWillMount() {
    // 取出携带的state
    const product = this.props.location.state // 如果是添加则没值，修改则有值
    // 保存是否为更新的标识（是否从更新按钮中跳转过来）
    this.isUpdate = !!product

    this.product = product || {}
  }

  form = React.createRef()
  editor = React.createRef()

  render() {
    const { isUpdate, product } = this
    const { pCategoryId, categoryId } = product

    console.log(product);

    const categoryIds = []
    if (isUpdate) {
      if (pCategoryId === '9') {
        categoryIds.push(pCategoryId)
      } else {
        categoryIds.push(pCategoryId)
        categoryIds.push(categoryId)
      }
    }

    const { options } = this.state

    const formItemLayout = {
      labelCol: { span: 1 },
      wrapperCol: { span: 8 }
    }

    const title = (
      <span>
        <LinkButton>
          <ArrowLeftOutlined style={{ color: 'green', marginRight: 10, fontSize: 20 }}
            onClick={() => this.props.history.goBack()} />
        </LinkButton>
        <span>{isUpdate ? '修改商品' : '添加商品'}</span>
      </span>
    )

    const onFinish = async (values) => {
      console.log(values);
      // console.log(this.editor.current.getDetail());
      const product = values;
      product.detail = this.editor.current.getDetail();
      if (product.options.length === 2) {
        product.pCategoryId = product.options[0] || '';
        product.categoryId = product.options[1] || '';
      } else {
        product.categoryId = product.options[0] || ''
      }
      const { data: result } = await reqAddProduct(product)
      if(result.status === 0) {
        message.success('添加成功')
        this.forceUpdate();
      } else {
        message.error('添加失败')
      }
    };

    const onFinishFailed = (errorInfo) => {
      const { errorFields } = errorInfo
      errorFields.forEach(item => {
        const error = item.errors[0]
        message.error(error)
      })
    };

    const loadData = async selectedOptions => {
      const targetOption = selectedOptions[0];
      const { data: result } = await reqCategorys(targetOption.value)
      if (result.data.length <= 0) {
        targetOption.isLeaf = true;
      } else {
        let children = []
        // targetOption.children = result.data;
        result.data.forEach(item => {
          children.push({ value: item._id, label: item.name })
        })
        targetOption.children = children;
        this.setState({ options })
      }
    };

    return (
      <Card title={title}>
        <Form
          ref={this.form}
          {...formItemLayout}
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          initialValues={{
            name: product.name,
            desc: product.desc,
            price: product.price
          }}
        >
          <Item label="商品名称" name="name" defaultValue={product.name} rules={[{ required: true, whitespace: true, message: '请输入商品名称' }]}>
            <Input placeholder="请输入商品名称"></Input>
          </Item>
          <Item label="商品描述" name="desc" defaultValue={product.desc} rules={[{ required: true, whitespace: true, message: '请输入商品描述' }]}>
            <TextArea placeholder="请输入商品描述" autosize={{ minRows: 2, maxRow: 6 }}></TextArea>
          </Item>
          <Item label="商品价格" name="price" defaultValue={product.price} rules={[{ required: true, whitespace: true, message: '请输入价格' }, { validator: this.validatePrice }]}>
            <Input placeholder="请输入商品价格" addonAfter="元" type='number'></Input>
          </Item>
          <Item label="商品分类" name="options" rules={[{ required: true, message: '请选择分类' }]}>
            <Cascader
              placeholder="请选择分类"
              options={options}
              loadData={loadData}
              expandTrigger={'hover'}
              defaultValue={options}
            />
          </Item>
          <Item label="商品图片">
            <PicturesWall></PicturesWall>
          </Item>
          <Item label="商品详情">
            <RichTextEditor ref={this.editor}></RichTextEditor>
          </Item>
          <Item>
            <Button type="primary" htmlType="submit" >提交</Button>
          </Item>
        </Form>
      </Card>
    )
  }
}
